import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;


import org.apache.log4j.Logger;

public class SystemSafety {

	private static final Logger logger = Logger.getLogger(SystemSafety.class);
	private static final String JAVA_BRIDGETROLL = "gatekeeper";
    static RandomAccessFile raf ;
    static FileChannel channel ;
    static FileLock lock = null;
	public static void turnOn() throws IOException{
		raf = new RandomAccessFile(JAVA_BRIDGETROLL, "rw");
		channel = raf.getChannel();
        for(int l = 0; l < 60; l++) {
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            try {
                lock = channel.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }
            if(lock != null) break;
            try {
                Thread.sleep(l * 2000);
            } catch (Exception es) {}
            //log.info("Waiting in queue...");
        }
        if(lock == null) logger.info("ERROR: getEmail: couldn't lock the " + JAVA_BRIDGETROLL);
	}
	public static void turnOff() throws IOException{
        if(lock != null) lock.release();
        raf.close();
	}
}
